<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="showAddCatDialog" type="primary"> 添加分类 </el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        class="tree-table"
        index-text="#"
        border
        :show-row-hover="false"
        show-index
        :expand-type="false"
        :selection-type="false"
        :data="catelist"
        :columns="columns"
      >
        <template slot="isOK" slot-scope="scope">
          <i style="color: lightgreen" v-if="scope.row.cat_deleted === false" class="el-icon-success"></i>
          <i style="color: red" v-else class="el-icon-error"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini" type="">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" size="mini" type="success">二级</el-tag>
          <el-tag v-else size="mini" type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button size="mini" @click="showEditCatDialog(scope.row.cat_id)" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" @click="removeCateById(scope.row.cat_id)" type="danger" icon="el-icon-delte">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCatDialogVisible" @close="addCatDialogClosed" width="50%">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            change-on-select
            expand-trigger="hover"
            :props="cate_props"
            :options="parentCatlist"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类信息对话框 -->
    <el-dialog title="修改分类" :visible.sync="editCatDialogVisible" @close="eidtCatDialogClosed">
      <el-form :model="editCateForm" :rules="addCateFormRules" ref="editCateFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            change-on-select
            expand-trigger="hover"
            :props="cate_props"
            :options="parentCatlist"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      catelist: [],
      parentCatlist: [],
      cate_props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },

      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      editCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      total: 0,
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', type: 'template', template: 'isOK' },
        { label: '排序', type: 'template', template: 'order' },
        { label: '操作', type: 'template', template: 'opt' }
      ],
      addCatDialogVisible: false,
      selectedKeys: [],
      editCatDialogVisible: false
    }
  },
  created() {
    this.getCatelist()
  },
  methods: {
    async getCatelist() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类信息失败')
      } else {
        this.catelist = res.data.result

        this.total = res.data.total
      }
    },
    async getParentCatelist() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败')
      }
      this.parentCatlist = res.data
      console.log(res)
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCatelist()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCatelist()
    },
    showAddCatDialog() {
      this.getParentCatelist()
      this.addCatDialogVisible = true
    },
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_level = this.selectedKeys.length
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
      } else {
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      }
    },
    addCatDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.addCateForm = {}
      this.selectedKeys = []
    },
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.addCatDialogVisible = false
        this.getCatelist()
      })
    },
    async removeCateById(id) {
      const confirmResult = await this.$confirm('是否永久删除此分类？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((e) => e)
      if (confirmResult === 'cancel') {
        return this.$message.info('已取消删除操作')
      }
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.$message.success('删除分类成功')
      this.getCatelist()
    },
    async showEditCatDialog(id) {
      // 查询商品分类信息
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询商品分类失败')
      }
      this.editCateForm = res.data
      this.getParentCatelist()
      this.selectedKeys = await this.getCatePath(res.data.cat_pid)
      this.editCatDialogVisible = true
    },
    async getCatePath(id) {
      const selectedPath = [id]
      while (id !== 0) {
        const cate = await this.getCateById(id)
        selectedPath.push(cate.cat_id)
        id = cate.cat_pid
      }
      return selectedPath.reverse()
    },
    async getCateById(id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询商品分类失败')
      }
      return res.data
    },
    eidtCatDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
      this.editCateForm = {}
      this.selectedKeys = []
    },
    editCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, this.editCateForm)
        if (res.meta.status !== 200) {
          return this.$message.error('更改分类失败')
        }
        this.$message.success('更新分类成功')
        this.getCatelist()
        this.editCatDialogVisible = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.tree-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>